package com.jsaas.core.security;

import java.io.Serializable;

import javax.servlet.ServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.apache.shiro.web.session.mgt.WebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**   
 * @Title: MyWebSessionManager.java 
 * @Package com.jsaas.core.security 
 * @Description: TODO(自定义WebSessionManager，用于替代DefaultWebSessionManager；) 
 * @author tuozq 
 * @date 2017年12月6日 上午11:24:53 
 * @version V1.0   
 */
public class MyWebSessionManager extends DefaultWebSessionManager implements WebSessionManager {
	private static final Logger log = LoggerFactory.getLogger(MyWebSessionManager.class);

	public MyWebSessionManager() {
		Cookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
		cookie.setHttpOnly(true); // more secure, protects against XSS attacks
		super.setSessionIdCookie(cookie);
		super.setSessionIdCookieEnabled(true);
	}

	/**
	 * Modify By tuozq
	 * 讲session放到request中，避免多次调用sessionDao中doReadSession方法
	 */
	@Override
	protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
		Serializable sessionId = getSessionId(sessionKey);
		if (sessionId == null) {
			log.debug("Unable to resolve session ID from SessionKey [{}].  Returning null to indicate a "
					+ "session could not be found.", sessionKey);
			return null;
		}


		// ***************Add By tuozq****************
		ServletRequest request = null;
		if (sessionKey instanceof WebSessionKey) {
			request = ((WebSessionKey) sessionKey).getServletRequest();
		}

		if (request != null) {
			Object s = request.getAttribute(sessionId.toString());
			if (s != null) {
				return (Session) s;
			}
		}
		// ***************Add By tuozq****************


		Session s = retrieveSessionFromDataSource(sessionId);
		if (s == null) {
			// session ID was provided, meaning one is expected to be found, but
			// we couldn't find one:
			String msg = "Could not find session with ID [" + sessionId + "]";
			throw new UnknownSessionException(msg);
		}



		// ***************Add By tuozq****************
		if (request != null) {
			request.setAttribute(sessionId.toString(),s);
		}
		// ***************Add By tuozq****************


		return s;
	}
	

	/**
	 * This is a native session manager implementation, so this method returns
	 * {@code false} always.
	 *
	 * @return {@code false} always
	 * @since 1.2
	 */
	public boolean isServletContainerSessions() {
		return false;
	}

}
